<?php

namespace app\common\helper\payment;

use EasyWeChat\Factory;

use app\common\logic\DataSettingLogic;

use app\common\model\ShopPaymentModel;

use app\common\model\ShopModel;

use think\Exception;



class PaymentBaseHelper{

    protected  $moudel = 'yoga';

    protected  $orderKey = 'balance';

    protected  $respondAction = 'balanceRespond';

    protected  $payType = 0;

    protected  $app;

    protected  $shopId;

    public function __construct($shopId) {

        $DataSettingLogic = new DataSettingLogic();

        $config = $DataSettingLogic->getData('payment');

        $shopInfo = ShopModel::find($shopId);

        $payment = ShopPaymentModel::find($shopId);

        if(null === $payment){

            throw  new Exception('暂未配置支付信息');

        }

      

        $this->shopId = $shopId;

        $this->payType = $payment->type; //支付类型赋值 下面会需要

        $path = $this->getCertDir();

        $payConfig = [];

        if($payment->type == 1){ //服务商支付

            $certFile = $path . md5($config['ser_api_cert']).'_cert.perm';

            if(!file_exists($certFile)){

                 file_put_contents($certFile, $config['ser_api_cert']);

            }

            $keyFile  = $path . md5($config['ser_api_key']).'_key.perm';

            if(!file_exists($keyFile)){

                 file_put_contents($keyFile, $config['ser_api_key']);

            }

            $payConfig = [

                'app_id'            => $config['ser_app_id'],

                'mch_id'            => $config['ser_mach_id'],

                'sub_appid'         => $shopInfo->wx_app_id,

                'sub_mch_id'        => $payment->service_mach_id,

                'key'               => $config['ser_api_auth'],

                'cert_path'         => $certFile,

                'key_path'          => $keyFile,

                'notify_url'        => $this->getBackUrl(),

            ];

        }else{
            $certFile = $path . md5($payment->api_cert).'_cert.perm';

            if(!file_exists($certFile)){

                file_put_contents($certFile, $payment->api_cert);

            }

            $keyFile  = $path . md5($payment->api_key).'_key.perm';

            if(!file_exists($keyFile)){

                file_put_contents($keyFile, $payment->api_key);

            }

            $payConfig = [

                'app_id'         => $shopInfo->wx_app_id,

                'mch_id'         => $payment->mach_id,

                'key'            => $payment->api_auth,

                'cert_path'      => $certFile,

                'key_path'       => $keyFile,

                'notify_url'     => $this->getBackUrl(),

            ];


        }
        //wyuLog('text3.txt', $this->getBackUrl());

        $this->app = Factory::payment($payConfig);

    }

    protected function getBackUrl(){ //返回支付回调URL

        return 'http://i.uumo.top/'.$this->moudel.'/miniapp/'.$this->respondAction.'/'.$this->shopId;

    }
    

    /**

     * @params $order  外面的订单 ['product_name' => '','order_id' => '123456','need_pay' => '','open_id' => ''] 

     * @return  $array 微信支付的参数

     */

    public  function getPayment($order){

        if(empty($order['product_name']) || empty($order['order_id']) || empty($order['need_pay']) || empty($order['open_id'])){

            return false;

        }

        $unifyOrder = [

            'body' => $order['product_name'],

            'out_trade_no' => $this->orderKey.'_'.rand(1000,9999).'_'. $order['order_id'], //增加4位随机数防止订单号的重复

            'total_fee' => $this->shopId == 20210021 ? '1': (int)($order['need_pay'] * 100),//调试设置为1

            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型

        ];

        if($this->payType == 1){

            $unifyOrder['sub_openid'] = $order['open_id'];

        }else{

            $unifyOrder['openid'] = $order['open_id'];

        }

        $return = $this->app->order->unify($unifyOrder);

        if($return['return_code'] == 'SUCCESS'){

            return $this->app->jssdk->bridgeConfig($return['prepay_id'], false);

        }

        return false;

    }

    public function respond(){

        $self = $this;

        $response = $this->app->handlePaidNotify(function($message, $fail) use ($self){

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态

                if ($message['result_code'] === 'SUCCESS') { //支付成功

                    $info = explode('_',$message['out_trade_no']);

                    if($info[0] == $this->orderKey){

                        $self->respondCallback($info[2], $message,$fail);

                    }

                }

            } else {

                return $fail('通信失败，请稍后再通知我');

            }

            return true; // 返回处理完成

        });

        $response->send();

    }

    

    //支付后回调

    public function respondCallback($orderId,$payInfo,$fail){



    }

    

    public function refundInTheSameWay($payInfo){

        $app = $this->app;
        return $app->refund->byTransactionId($payInfo['transaction_id'], $payInfo['out_trade_no'], $payInfo['total_fee'], $payInfo['total_fee']);

    } 

    



    

    protected function getCertDir(){

        $dir = root_path().'/cert/shop/';

        if(!is_dir($dir)){

            mkdir($dir,0755,true);

        }

        return $dir;

    }

}